<template>
  <div class="inmaplove-page">
    <!-- 左上角搜索卡片 -->
    <div class="search-card">
      <el-card shadow="hover" class="search-card-inner">
        <el-input
          v-model="searchText"
          placeholder="搜索用餐地点/备注"
          clearable
          size="default"
          style="margin-bottom: 8px"
        />
        <div class="search-list">
          <div
            v-for="point in pagedPoints"
            :key="`${point.location}-${point.longitude}-${point.latitude}`"
            class="search-list-item"
            @click="handleListClick(point)"
          >
            <div class="item-title" :title="point.location">
              {{ point.location }}
            </div>
            <div class="item-desc">
              <el-tag size="small" :type="getTypeTagType(point.type)">{{
                point.type
              }}</el-tag>
              <span>打卡 {{ point.count }} 次</span>
            </div>
          </div>
          <div v-if="pagedPoints.length === 0" class="empty-tip">
            暂无匹配记录
          </div>
        </div>
        <el-pagination
          v-if="filteredPoints.length > pageSize"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="filteredPoints.length"
          layout="prev, pager, next"
          size="small"
          style="margin-top: 4px; text-align: center"
          @current-change="handlePageChange"
        />
      </el-card>
    </div>
    <div ref="mapContainer" class="map-container" />
  </div>
</template>

<script lang="ts">
declare global {
  interface Window {
    AMap: any;
  }
}
</script>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElTag } from "element-plus";
import { Location, Search, LocationFilled } from "@element-plus/icons-vue";
import { getMapPoints, type MapPoint } from "@/api/love/map";

const typeOptions = ["吃饭", "游玩", "爬山", "吵架", "逛街"];

function getTypeTagType(type: string) {
  switch (type) {
    case "吃饭":
      return "success";
    case "游玩":
      return "primary";
    case "爬山":
      return "warning";
    case "吵架":
      return "danger";
    case "逛街":
      return "info";
    default:
      return "info";
  }
}

const points = ref<MapPoint[]>([]);
const loading = ref(true);

const mapContainer = ref();
let map = null;
const router = useRouter();

// 搜索相关
const searchText = ref("");
const currentPage = ref(1);
const pageSize = 5;
const filteredPoints = computed<MapPoint[]>(() => {
  if (!searchText.value) return points.value;
  const keyword = searchText.value.toLowerCase();
  return points.value.filter(
    p =>
      p.location.toLowerCase().includes(keyword) ||
      p.count.toString().includes(keyword) ||
      p.lastDate.toLowerCase().includes(keyword)
  );
});
const pagedPoints = computed<MapPoint[]>(() => {
  const start = (currentPage.value - 1) * pageSize;
  return filteredPoints.value.slice(start, start + pageSize);
});

// marker 和 infoWindow 引用管理
const markerMap = new Map(); // key: id, value: { marker, infoWindow }

function setupInfoWindow(point: MapPoint) {
  // AMap InfoWindow 内容是动态添加到 DOM 的，需要短暂延迟来确保能获取到元素
  setTimeout(() => {
    const btnId = `gotoDiningBtn-${point.location}-${point.longitude}-${point.latitude}`;
    const btn = document.getElementById(btnId);
    if (btn) {
      btn.onclick = () => {
        router.push({
          path: "/love/dining",
          query: { location: point.location }
        });
      };
    }
    // 获取信息窗体 DOM，并阻止其内部滚动时缩放地图
    const infoEl = btn?.closest(".info-window-v3");
    if (infoEl) {
      const stopPropagation = e => e.stopPropagation();
      infoEl.addEventListener("wheel", stopPropagation);
      infoEl.addEventListener("mousewheel", stopPropagation);
      infoEl.addEventListener("DOMMouseScroll", stopPropagation);
    }
  }, 100);
}

function getIconByLocation(location) {
  if (location.includes("咖啡")) {
    return "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-coffee.png"; // 咖啡杯icon
  }
  if (location.includes("麦当劳") || location.includes("汉堡")) {
    return "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-burger.png"; // 汉堡icon
  }
  if (
    location.includes("餐") ||
    location.includes("饭") ||
    location.includes("必胜客")
  ) {
    return "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-rest.png"; // 餐饮icon
  }
  // 默认
  return "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png";
}

function openInfoWindowByPoint(point: MapPoint) {
  if (!map) return;
  const markerKey = `${point.location}-${point.longitude}-${point.latitude}`;
  const refObj = markerMap.get(markerKey);
  if (refObj) {
    map.setCenter([point.longitude, point.latitude]);
    refObj.infoWindow.open(map, [point.longitude, point.latitude]);
    setupInfoWindow(point);
  }
}

function handleListClick(point: MapPoint) {
  openInfoWindowByPoint(point);
}

function handlePageChange(page: number) {
  currentPage.value = page;
}

function handleSearch() {
  currentPage.value = 1;
}

function initMap() {
  if (!window.AMap) {
    ElMessage.error("高德地图未加载");
    loading.value = false;
    return;
  }
  map = new window.AMap.Map(mapContainer.value, {
    resizeEnable: true,
    zoom: 12,
    center: [108.95, 34.27],
    viewMode: "2D"
  });
  points.value.forEach((point, idx) => {
    const marker = new window.AMap.Marker({
      position: [point.longitude, point.latitude],
      title: point.location,
      icon: getIconByLocation(point.location)
    });
    marker.setMap(map);

    const btnId = `gotoDiningBtn-${point.location}-${point.longitude}-${point.latitude}`;
    const info = `
        <div class='info-window-v3' style='padding: 2px; font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; width: 180px;'>
          <div title="${point.location}" style='font-size:16px; font-weight:600; color:#303133; margin-bottom: 8px; text-align: center; border-bottom: 1px solid #f2f2f2; padding-bottom: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>${point.location}</div>
          <div style='font-size:12px; color:#909399; margin-bottom:10px; text-align: center;'>
            <span>已打卡 ${point.count} 次</span>
          </div>
          <button id='${btnId}' style='background-color: #f7f7f7; border: 1px solid #e5e5e5; color: #333; border-radius:4px; padding: 6px 0; cursor:pointer; font-size: 12px; width: 100%; box-sizing: border-box; text-align: center;'>
            查看${point.type}详情
          </button>
        </div>
      `;
    const infoWindow = new window.AMap.InfoWindow({
      content: info,
      offset: new window.AMap.Pixel(0, -30)
    });

    marker.on("click", () => {
      infoWindow.open(map, marker.getPosition());
      setupInfoWindow(point);
    });

    // 保存 marker 和 infoWindow 引用
    const markerKey = `${point.location}-${point.longitude}-${point.latitude}`;
    markerMap.set(markerKey, { marker, infoWindow });

    // 默认展开第一个点的 InfoWindow
    if (idx === 0) {
      infoWindow.open(map, marker.getPosition());
      setupInfoWindow(point);
    }
  });
}

onMounted(() => {
  getMapPoints()
    .then(res => {
      points.value = res;
      if (res.length === 0) {
        ElMessage.info("暂无打卡记录");
      }
      nextTick(() => {
        initMap();
      });
    })
    .catch(err => {
      console.error(err);
      ElMessage.error("获取打卡数据失败");
    })
    .finally(() => {
      loading.value = false;
    });
});
</script>

<style scoped>
html,
body {
  overflow: hidden !important;
  height: 100%;
}
.inmaplove-page {
  overflow: hidden !important;
  width: 100vw;
  height: calc(100vh - 60px);
  min-height: 500px;
  position: relative;
}
.map-container {
  overflow: hidden !important;
  width: 100%;
  height: 100%;
}
.search-card {
  position: absolute;
  top: 18px;
  left: 18px;
  z-index: 10;
  width: 320px;
  background: transparent;
}
.search-card-inner {
  padding: 12px 12px 4px 12px;
  border-radius: 0 !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}
.search-list {
  background: transparent !important;
  border-radius: 0;
  padding: 0;
  margin-top: 12px;
}
.search-list-item {
  padding: 8px 0 6px 0;
  border-bottom: 1px solid #f2f2f2;
  cursor: pointer;
  transition: background 0.2s;
}
.search-list-item:last-child {
  border-bottom: none;
}
.search-list-item:hover {
  background: #f7f7fa;
}
.item-title {
  font-size: 15px;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.item-desc {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.empty-tip {
  text-align: center;
  color: #bbb;
  font-size: 13px;
  margin-top: 16px;
}
.info-window-v3 {
  max-height: 150px;
  overflow: auto;
}
/* 卡片无圆角 */
.search-card,
.search-card-inner,
.el-card {
  border-radius: 0 !important;
}

/* 搜索框扁平风格 */
.search-input-flat .el-input__wrapper {
  border-radius: 0 !important;
  background: #fff;
  border: 1px solid #e5e6eb;
  box-shadow: none;
  padding-left: 0;
}
.search-input-flat .el-input__inner {
  font-size: 16px;
  color: #333;
  background: transparent;
}
.search-logo {
  width: 32px;
  height: 32px;
  margin-right: 4px;
  border-radius: 0;
  object-fit: contain;
}
.search-input-flat .el-input__suffix {
  margin-right: 8px;
}
</style>

<style>
html,
body,
#app,
.grow,
.inmaplove-page,
.map-container {
  height: 100% !important;
  min-height: 0 !important;
  width: 100% !important;
  min-width: 0 !important;
  overflow: hidden !important;
  box-sizing: border-box !important;
  padding: 0 !important;
  margin: 0 !important;
}
/* 隐藏高德地图所有滚动条 */
.amap-container,
.amap-maps,
.amap-layers,
.amap-controls,
.amap-overlays {
  scrollbar-width: none !important; /* Firefox */
  -ms-overflow-style: none !important; /* IE 10+ */
}
.amap-container::-webkit-scrollbar,
.amap-maps::-webkit-scrollbar,
.amap-layers::-webkit-scrollbar,
.amap-controls::-webkit-scrollbar,
.amap-overlays::-webkit-scrollbar {
  display: none !important; /* Chrome/Safari/Edge */
}
[class^="amap-"],
[class*=" amap-"] {
  scrollbar-width: none !important;
  -ms-overflow-style: none !important;
}
[class^="amap-"]::-webkit-scrollbar,
[class*=" amap-"]::-webkit-scrollbar {
  display: none !important;
}
</style>
